package com.idc.quotation.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.idc.common.cache.RedisClient;
import com.idc.common.constant.ErrorCode;
import com.idc.common.constant.RedisKey;
import com.idc.common.mvc.vo.ResponseVo;
import com.idc.common.util.DateUtil;
import com.idc.common.util.JwtUtil;
import com.idc.quotation.config.LoginConfig;
import com.idc.quotation.service.LoginService;

@Service
public class LoginServiceImpl implements LoginService, RedisKey {

	@Autowired
	private RedisClient redisClient;
	@Autowired
	private JwtUtil jwtUtil;
	@Autowired
	private LoginConfig loginConfig;

	@Override
	public ResponseVo<?> smsCodeLogin(String mdn, String code) {
		ResponseVo<?> checkVo = checkSmsCode(mdn, code);
		if (!checkVo.getStatus()) {
			return checkVo;
		}
		Map<String, Object> claims = new HashMap<>();
		claims.put("mobile", mdn);
		String token = jwtUtil.generateToken(mdn);
		redisClient.set(LOGIN_TOKEN_KEY + mdn, token, loginConfig.getTokenExpirationTime() * 3600);
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("token", token);
		return ResponseVo.success(dataMap);
	}

	@Autowired
	private LoginConfig config;

	public ResponseVo<?> checkSmsCode(String mobile, String code) {
		String ftime = redisClient.get(LOGIN_SMSCODE_FREEZE + mobile);
		if (!StringUtils.isEmpty(ftime)) {
			String time = DateUtil.toString(DateUtil.parseDate(ftime, "yyyy-MM-dd HH:mm:ss"), "HH:mm:ss");
			return ResponseVo.fail(-1, "验证码连续校验错误，请在" + time + "后重试");
		}
		String redisCode = redisClient.get(LOGIN_VERIFICATION_CODE + mobile);
		if (code.equals(redisCode)) {
			redisClient.del(LOGIN_VERIFICATION_CODE + mobile);
			redisClient.del(LOGIN_SMSCODE_ERRORTIMES + mobile);
			return ResponseVo.success();
		} else {
			int errorTimes = config.getErrorTimes();
			if (errorTimes == 0) {
				errorTimes = 5;
			}
			long times = redisClient.incr(LOGIN_SMSCODE_ERRORTIMES + mobile);
			if (times >= errorTimes) {
				redisClient.set(LOGIN_SMSCODE_FREEZE + mobile, DateUtil.toString(new Date(System.currentTimeMillis() + 3600 * 1000L), "yyyy-MM-dd HH:mm:ss"), 3600);
				return ResponseVo.fail(-1, "验证码连续校验错误达到" + errorTimes + "次，账号冻结");
			}
			if (StringUtils.isEmpty(redisCode)) {
				return ResponseVo.fail(ErrorCode.LOGIN_SMSCODE_TIMEOUT);
			}
			return ResponseVo.fail(ErrorCode.LOGIN_SMSCODE_ERROR);
		}
	}
}
